import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.CountDownLatch;

import javax.swing.*;


public class LoginPanel extends JPanel implements ActionListener {
	
	public static final int width = 400;
	public static final int height = 200;
	
	//private boolean loggedIn = false;
	
	private JLabel title;
	private JButton loginButton;
	private JPasswordField passwordField;
	private JLabel status;
	
	CountDownLatch loginSignal;
	
	public LoginPanel(CountDownLatch ls) {
		
		setLayout(null);
		add(getTitle());
		add(getLoginButton());
		add(getPasswordField());
		add(getStatus());
		setSize(width,height);
		loginSignal = ls;
		
	}
	
	private JLabel getTitle() {
		if (title == null){
			title = new JLabel("Please enter pin-code:");
			title.setBounds(100, 40, 200, 20);
		}
		return title;
	}

	private JButton getLoginButton() {
		if (loginButton == null){
			loginButton = new JButton("Login");
			loginButton.setBounds(100, 120, 200, 30);
			loginButton.addActionListener(this);
		}
		return loginButton;
	}
	
	private JPasswordField getPasswordField() {
		if (passwordField == null){
			passwordField = new JPasswordField();
			passwordField.setBounds(100, 80, 200, 30);
		}
		return passwordField;
	}
	
	private JLabel getStatus() {
		if (status == null){
			status = new JLabel(" ");
			status.setBounds(100, 160, 200, 20);
		}
		return status;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == getLoginButton()){
			String stringPass = "";
			char[] pass = getPasswordField().getPassword();
			for(int i = 0; i < pass.length; i++)
				stringPass = stringPass + pass[i];
			if(stringPass.equals("scatcat")){
				status.setForeground(Color.green);
				status.setText("Correct password!");
				loginSignal.countDown();
			}
			else{
				status.setForeground(Color.red);
				status.setText("Incorrect password!");
			}
			passwordField.setText("");
		}
	}
	
//	public void waitForLogin() {
//		
//		while(!loggedIn){
//			try {
//				Thread.sleep(10);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//		}
//		
//	}

}
